package com.hblack.manage.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hblack.manage.mapper.ContentCategoryMapper;
import com.hblack.manage.pojo.ContentCategory;

@Service
public class ContentCategoryService extends BaseService<ContentCategory> {
	
	@Autowired
	private ContentCategoryMapper contentCategoryMapper;

	/**
	 * 保存
	 * @param contentCategory
	 * @return
	 */
	public Boolean saveContentCategory(ContentCategory contentCategory) {
		
		contentCategory.setId(null);
		contentCategory.setIsParent(false);
		contentCategory.setSortOrder(1);
		contentCategory.setStatus(1);
		int saveCount = save(contentCategory);
		if(saveCount != 1) {
			return false;
		}
		
		ContentCategory parent = this.contentCategoryMapper.selectByPrimaryKey(contentCategory.getParentId());
		if(!parent.getIsParent()) {
			parent.setIsParent(true);
			int saveParentCount = super.updateByPrimaryKey(parent);
			if(saveParentCount != 1) {
				throw new RuntimeException("修改父类节点状态失败");
			}
		}
		
		return true;
	}

	/**
	 * 删除
	 * @param contentCategory
	 * @return
	 */
	public Boolean deleteContentCategory(ContentCategory contentCategory) {
		
		ArrayList<Object> ids = new ArrayList<>();
		ids.add(contentCategory.getId());
		
		//根据id查出要删除的对象 
		ContentCategory self = super.queryById(contentCategory.getId());
		if(self.getIsParent()){
			//如果是父类，查询出所有子节点，并将所有子节点的id添加到要删除的list
			queryChildrenIds(self.getId(),ids);
		}
		//根据要删除的id的集合删除自身和子节点
		Integer deleteCount = super.deleteByIds(ContentCategory.class, "id", ids);
		if(deleteCount == 0){
			new RuntimeException("删除商品类目失败，contentCategory：" + self);
		}
		
		//查询出是否有兄弟节点，如果没有，将父类的是否为父节点改为false
		ContentCategory queryParentE = new ContentCategory();
		queryParentE.setParentId(contentCategory.getParentId());
		List<ContentCategory> list = queryListByWhere(queryParentE);
		if(list == null || list.size() == 0){
			ContentCategory parent = new ContentCategory();
			parent.setId(contentCategory.getParentId());
			parent.setIsParent(false);
			super.updateByPrimaryKey(parent);
		}
		
		return true;
	}

	/**
	 * 根据ID查询所有子节点
	 * @param id
	 * @param ids
	 */
	private void queryChildrenIds(Long id, ArrayList<Object> ids) {
		
		ContentCategory queryE = new ContentCategory();
		queryE.setParentId(id);
		List<ContentCategory> list = super.queryListByWhere(queryE);
		
		for (ContentCategory contentCategory : list) {
			ids.add(contentCategory.getId());
			if(contentCategory.getIsParent()){
				queryChildrenIds(contentCategory.getId(),ids);
			}
		}
	}

}
